package com.appcommon;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ConnectDataBase {
	
	private String databaseType;
	private String driver = "com.mysql.jdbc.Driver";
	private String url = "jdbc:mysql://127.0.0.1:3306/stuinfo";
	private ResultSet resultSet;
	private Connection connection;
	private Statement statement;
	private String sqlString;
	
	
	public ConnectDataBase(String database) {
		this.databaseType = database;
		sqlString = "select * from " + databaseType;
	}
	//数据库连接
	public void connect() {
		try {
			//加载驱动
			Class.forName(driver);
			//创建连接
			connection = DriverManager.getConnection(url, "root", "hq1100100"); //数据库的账号密码要改动
			statement = connection.createStatement();
			
			 
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public Connection getConnection() {
		return connection;
	}
	//把resultSet设置getter方法
	public ResultSet getResultSet() {
		try {
			//查询后的返回结果集
//			System.out.println(sqlString);
			resultSet = statement.executeQuery(sqlString);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return resultSet;
	}
	
	//关闭相关连接
	public void close() {
		try {
			if (resultSet != null) {
				resultSet.close();
			}
			statement.close();
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
}
